﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace MockJson
{
    public partial class FrmEditApi : Form
    {
        private Api _api;
        private readonly Action _action;

        public FrmEditApi(Api api, Action action)
        {
            InitializeComponent();

            _api = api;
            _action = action;
            //修改
            if (!string.IsNullOrWhiteSpace(_api?.Id))
            {
                txtUrl.Text = _api.Url;
                cboMethod.Text = _api.Method;
                txtDescription.Text = _api.Description;
            }

            InitializeListView();
            ReloadApiResponses();

            cboMethod.Items.AddRange(new string[] { "POST" });
            cboMethod.SelectedIndex = 0;
        }

        private void ReloadApiResponses()
        {
            if (string.IsNullOrWhiteSpace(_api?.Id))
                return;

            var apis = App.DB.Queryable<ApiResponse>().Where(x => x.ApiId == _api.Id).ToList();
            if (apis.Count > 0)
            {
                this.listViewApiResponses.Items.Clear();
                this.listViewApiResponses.BeginUpdate();

                foreach (ApiResponse item in apis)
                {
                    ListViewItem lvi = new ListViewItem();
                    //lvi.ImageIndex = i; 

                    lvi.Tag = item;
                    lvi.Text = item.ContentType;
                    lvi.SubItems.Add(item.Weight.ToString());
                    lvi.SubItems.Add(item.Enable ? "启用" : "禁用");
                    lvi.SubItems.Add(item.Response);

                    this.listViewApiResponses.Items.Add(lvi);
                }

                this.listViewApiResponses.EndUpdate();
            }
        }

        private void InitializeListView()
        {
            listViewApiResponses.FullRowSelect = true;
            listViewApiResponses.View = View.Details;
            listViewApiResponses.MultiSelect = true;
            listViewApiResponses.Columns.Add("内容类型", 120, HorizontalAlignment.Left);//一步添加 
            listViewApiResponses.Columns.Add("权重", 80, HorizontalAlignment.Left); //一步添加  
            listViewApiResponses.Columns.Add("启用", 80, HorizontalAlignment.Left); //一步添加  
            listViewApiResponses.Columns.Add("返回值", 250, HorizontalAlignment.Left); //一步添加  
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var url = txtUrl.Text.Trim();
            if (string.IsNullOrEmpty(url))
            {
                txtUrl.Focus();
                return;
            }
            if (!url.StartsWith("/"))
            {
                MessageBox.Show("Url必须以/开头", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUrl.Focus();
                return;
            }

            var method = cboMethod.Text;

            //修改
            if (!string.IsNullOrWhiteSpace(_api?.Id))
            {
                _api.Url = url;
                _api.Method = method;
                _api.Description = txtDescription.Text;
                App.DB.Update<Api>().SetSource(_api).ExecuteAffrows();
            }
            else
            {
                var has = App.DB.Queryable<Api>().Any(x => x.Url == url && x.Method == method);
                if (has)
                {
                    MessageBox.Show("Url已经存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                _api = new Api
                {
                    Description = txtDescription.Text,
                    Method = cboMethod.Text,
                    Url = url,
                    Id = Guid.NewGuid().ToString(),
                };
                App.DB.Insert<Api>(_api).ExecuteAffrows();
            }


            App.DB.Delete<ApiResponse>().Where(x => x.ApiId == _api.Id).ExecuteAffrows();
            foreach (ListViewItem item in listViewApiResponses.Items)
            {
                var apiResponse = item.Tag as ApiResponse;
                apiResponse.ApiId = _api.Id;
                App.DB.Insert(apiResponse).ExecuteAffrows();
            }

            _action.Invoke();
            this.Close();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lblAdd_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new FrmEditResponse(null, item =>
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Tag = item;
                lvi.Text = item.ContentType;
                lvi.SubItems.Add(item.Weight.ToString());
                lvi.SubItems.Add(item.Enable ? "启用" : "禁用");
                lvi.SubItems.Add(item.Response);
                this.listViewApiResponses.Items.Add(lvi);
            }).ShowDialog();
        }

        private void lblEdit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var selects = listViewApiResponses.SelectedItems;
            if (selects.Count > 0)
            {
                ListViewItem selectedItem = selects[0];
                var api = selectedItem.Tag as ApiResponse;
                new FrmEditResponse(api, item =>
                {
                    selectedItem.SubItems[0].Text = item.ContentType;
                    selectedItem.SubItems[1].Text = item.Weight.ToString();
                    selectedItem.SubItems[2].Text = item.Enable ? "启用" : "禁用";
                    selectedItem.SubItems[3].Text = item.Response;

                    selectedItem.Tag = item;
                }).ShowDialog();
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var selects = listViewApiResponses.SelectedItems;
            if (selects.Count > 0)
            {
                foreach (ListViewItem item in selects)
                    listViewApiResponses.Items.RemoveAt(item.Index);
            }
        }

        private void listViewApiResponses_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            lblEdit_LinkClicked(sender, null);
        }
    }
}
